package com.example.recyclerviewtest.ItemDecoration;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;


/**
 *
 * 
 * @name
 * @className DividerGridItemDecoration
 * @author shaoyance     
 * @changer 
 * @chang 上午10:22
 * @description 转自Android RecyclerView 使用完全解析 体验艺术般的控件(https://blog.csdn.net/lmj623565791/article/details/45059587)
 * 20-12-16 上午10:22 Create DividerGridItemDecoration.java by shaoyance;
 *
 * // FIXME: 20-12-16  存在的问题
 * 当数据铺满全屏的时候最后一行还是有分割线
 *
 *
 * 
 */
public class DividerGridItemDecoration extends RecyclerView.ItemDecoration {

    private static final String TAG = "DividerGridItemDecorati";

    private static final int[] ATTRS = new int[] { android.R.attr.listDivider };
    private Drawable mDivider;

    public DividerGridItemDecoration(Context context)
    {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state)
    {

        drawHorizontal(c, parent);
        drawVertical(c, parent);

    }

    private int getSpanCount(RecyclerView parent)
    {
        // 列数
        int spanCount = -1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager)
        {

            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager)
        {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        return spanCount;
    }

    /**
     * 画水平方向的分割线
     *
     * 水平方向的分割线其实就是一个矩形， 它由的位置由左上角和右下角两个点的坐标确定。
     * 左上的坐标为(left, top)
     * 右下的坐标(right, bottom)
     *
     * left： child的左边那条边的值 - child View layout_marginLeft的值
     * top: child的底部那条边的值 + child View layout_marginBottom的值
     * right： child的右边那条边的值 + chiild View layout_marginRigth的值 + 分割线的宽度
     * bottom：  top + 分割线的高度
     *
     * 可以将子view设置为1个来观察一下水平方向的分割线是如何绘制的。
     * 竖直方向的分割线原理和水平方向的分割线类似。
     *
     * @param c
     * @param parent
     */
    public void drawHorizontal(Canvas c, RecyclerView parent)
    {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getLeft() - params.leftMargin;
            final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();

            Log.e(TAG, "drawHorizontal: mDivider.getIntrinsicWidth() :"+   mDivider.getIntrinsicWidth());
            Log.e(TAG, "drawHorizontal: mDivider.getIntrinsicHeight() :"+   mDivider.getIntrinsicHeight());
            Log.e(TAG, "drawHorizontal: = params.bottomMargin   :"+   params.bottomMargin  );
            Log.e(TAG, "drawHorizontal: = params.rightMargin   :"+    params.rightMargin  );

            Log.e(TAG, "drawHorizontal: left :"+  left);
            Log.e(TAG, "drawHorizontal: = child.getRight()  :"+  child.getRight() );
            Log.e(TAG, "drawHorizontal: right :"+  right);
            Log.e(TAG, "drawHorizontal: top :"+   top);
            Log.e(TAG, "drawHorizontal: = child.getBottom()   :"+   child.getBottom()  );
            Log.e(TAG, "drawHorizontal: bottom :"+   bottom);


            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }


    /**
     * 道理和 drawHorizontal 类似
     * @param c
     * @param parent
     */
    public void drawVertical(Canvas c, RecyclerView parent)
    {
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);

            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getTop() - params.topMargin;
            final int bottom = child.getBottom() + params.bottomMargin;
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicWidth();

            //top left
            Log.e(TAG, "drawVertical: child.getTop() :"+  child.getTop());
            Log.e(TAG, "drawVertical:  params.topMargin() :"+  params.topMargin);
            Log.e(TAG, "drawVertical: top :"+   top);
            Log.e(TAG, "drawVertical: child.getRight() :"+   child.getRight());
            Log.e(TAG, "drawVertical: left :"+   left);


            //right  bottom
            Log.e(TAG, "drawVertical: mDivider.getIntrinsicWidth() :"+   mDivider.getIntrinsicWidth());
            Log.e(TAG, "drawVertical: right :"+   right);
            Log.e(TAG, "drawVertical: child.getBottom() :"+   child.getBottom());
            Log.e(TAG, "drawVertical: params.bottomMargin :"+   params.bottomMargin);
            Log.e(TAG, "drawVertical: bottom :"+   bottom);

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
                                int childCount)
    {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager)
        {
            if ((pos + 1) % spanCount == 0)// 如果是最后一列，则不需要绘制右边
            {
                return true;
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager)
        {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            if (orientation == StaggeredGridLayoutManager.VERTICAL)
            {
                if ((pos + 1) % spanCount == 0)// 如果是最后一列，则不需要绘制右边
                {
                    return true;
                }
            } else
            {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最后一列，则不需要绘制右边
                    return true;
            }
        }
        return false;
    }

    private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,
                              int childCount)
    {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager)
        {
            childCount = childCount - childCount % spanCount;
            if (pos >= childCount)// 如果是最后一行，则不需要绘制底部
                return true;
        } else if (layoutManager instanceof StaggeredGridLayoutManager)
        {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            // StaggeredGridLayoutManager 且纵向滚动
            if (orientation == StaggeredGridLayoutManager.VERTICAL)
            {
                childCount = childCount - childCount % spanCount;
                // 如果是最后一行，则不需要绘制底部
                if (pos >= childCount)
                    return true;
            } else
            // StaggeredGridLayoutManager 且横向滚动
            {
                // 如果是最后一行，则不需要绘制底部
                if ((pos + 1) % spanCount == 0)
                {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
                               RecyclerView parent)
    {
        int spanCount = getSpanCount(parent);
        int childCount = parent.getAdapter().getItemCount();
        if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行，则不需要绘制底部
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列，则不需要绘制右边
        {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(),
                    mDivider.getIntrinsicHeight());
        }
    }

    /**
     * Sets the {@link Drawable} for this divider.
     *
     * @param drawable Drawable that should be used as a divider.
     */
    public void setDrawable(@NonNull Drawable drawable) {
        if (drawable == null) {
            throw new IllegalArgumentException("Drawable cannot be null.");
        }
        mDivider = drawable;
    }

    /**
     * @return the {@link Drawable} for this divider.
     */
    @Nullable
    public Drawable getDrawable() {
        return mDivider;
    }

}
